<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j page-register">
    <div class="r-header">
      <div class="content">
        <router-link
          to="/"
          class="logo"
        >
          <img
            v-if="webConfigData.pcLogoImgText"
            class="img"
            :src="webConfigData.pcLogoImgText"
            alt
          >
        </router-link>
        <div class="go-login">
          {{ $t('register.haveAnAccount') }}
          <router-link
            to="/login"
            class="login-btn"
          >
            {{ $t('register.goToLogin') }}
          </router-link>
        </div>
      </div>
    </div>
    <!-- 第一步 -->
    <div
      v-if="registerStep===1"
      class="r-con"
      :style="{margin:$t('language')==='en'?'80px auto':'100px auto'}"
    >
      <div class="steps">
        <div :class="['item', registerStep===1?'active':'']">
          <div class="number">
            1
          </div>
          <div class="text">
            {{ $t('register.verifyCellPhoneNumber') }}
          </div>
        </div>
        <div class="item">
          <div class="number">
            2
          </div>
          <div class="text">
            {{ $t('register.fillInTheAccountInformation') }}
          </div>
        </div>
        <div class="item">
          <div class="number">
            3
          </div>
          <div class="text">
            {{ $t('register.completeRegistration') }}
          </div>
        </div>
      </div>
      <div class="con-box">
        <div :class="['item',errorTips===1? 'error':'', 'item-bottom']">
          <div class="input-box phone">
            <span class="ic">+86</span>
            <input
              v-model="mobile"
              type="text"
              class="input"
              :placeholder="$t('login.enterUserNumber')"
              maxlength="11"
            >
          </div>
          <div
            v-if="errorTips===1"
            class="error-text"
          >
            {{ $t('register.enterValidPhone') }}
          </div>
        </div>
        <div :class="['item',errorTips===2? 'error':'', errorTips===2?'item-bottom':'']">
          <div class="input-box code">
            <input
              v-model="validCode"
              type="text"
              class="input"
              :placeholder="$t('login.enterCode')"
              maxlength="6"
            >
            <a
              v-show="show"
              href="javascript:void(0)"
              class="send-code"
              @click="getCode"
            >{{ $t('login.getCode') }}</a>
            <a
              v-show="!show"
              href="javascript:void(0)"
              class="send-code"
              style="cursor: not-allowed;"
            >{{ count }} s</a>
          </div>
          <div
            v-if="errorTips===2"
            class="error-text"
          >
            {{ $t('login.enterCode') }}
          </div>
        </div>
        <div class="item-bottom item agree">
          <div class="agreeTerms">
            <el-checkbox
              v-model="isAgree"
              :true-label="true"
              :false-label="false"
            />
            <div
              v-if="serviceTermsSwitch || privacyPolicySwitch"
              class="text"
            >
              {{ $t('login.consentOfRegisteredRepresentative') }}
              <a
                v-if="serviceTermsSwitch"
                href="javaScript:void(0)"
                class="agreement"
                @click="toTermsPage(0)"
              >{{ $t('login.termsOfService') }}</a>
              <span v-if="privacyPolicySwitch && serviceTermsSwitch">{{ $t('login.and') }}</span>
              <a
                v-if="privacyPolicySwitch"
                href="javaScript:void(0)"
                class="agreement"
                @click="toTermsPage(1)"
              >{{ $t('login.privacyPolicy') }}</a>
            </div>
          </div>
          <div
            v-show="errorTips === 6 && !isAgree"
            class="agreeTerms-error"
          >
            {{ $t('login.agreeTerms') }}
          </div>
        </div>
        <span
          class="next"
          @click="registerNext"
        >{{ $t('register.nextStep') }}</span>
      </div>
    </div>
    <!-- /第一步 -->
    <!-- 第二步 -->
    <div
      v-if="registerStep===2"
      class="r-con"
      :style="{margin:$t('language')==='en'?'80px auto':'100px auto'}"
    >
      <div class="steps">
        <div class="item active">
          <div class="number">
            1
          </div>
          <div class="text">
            {{ $t('register.verifyCellPhoneNumber') }}
          </div>
        </div>
        <div :class="['item', registerStep===2?'active':'']">
          <div class="number">
            2
          </div>
          <div class="text">
            {{ $t('register.fillInTheAccountInformation') }}
          </div>
        </div>
        <div class="item">
          <div class="number">
            3
          </div>
          <div class="text">
            {{ $t('register.completeRegistration') }}
          </div>
        </div>
      </div>
      <div class="con-box">
        <div :class="['item', 'item-bottom',errorTips===4 || errorTips===7? 'error':'']">
          <div class="input-box">
            <input
              v-model="password"
              v-input-rule
              type="password"
              maxlength="20"
              class="input"
              :placeholder="$t('register.pleaseSetYourPassword')"
            >
          </div>
          <div
            v-if="errorTips===4"
            class="error-text"
          >
            {{ $t('login.enterPassword') }}
          </div>
          <div
            v-if="errorTips===7"
            class="error-text"
          >
            {{ $t('register.passwordVerification') }}
          </div>
        </div>
        <div :class="['item', 'item-bottom',errorTips===5? 'error':'']">
          <div class="input-box">
            <input
              v-model="confirmPwd"
              v-input-rule
              type="password"
              class="input"
              maxlength="20"
              :placeholder="$t('register.enterThePasswordAgain')"
              @keyup.enter="registerNext"
            >
          </div>
          <div
            v-if="errorTips===5"
            class="error-text"
          >
            {{ $t('ucPassword.enterNewPasswordTips5') }}
          </div>
        </div>
        <span
          class="next"
          @click="registerNext"
        >{{ $t('register.nextStep') }}</span>
      </div>
    </div>
    <!-- /第二步 -->
    <!-- 第三步 -->
    <div
      v-if="registerStep===3"
      class="r-con"
      :style="{margin:$t('language')==='en'?'80px auto':'100px auto'}"
    >
      <div class="con-box">
        <div class="register-success">
          <div class="text">
            <div class="text-div">
              {{ $t('register.registrationSuccessful') }}
            </div>
            <div class="text-span">
              {{ $t('register.autoJumpToHome') }} <span style="color:blue">{{ loCount }} s</span>
            </div>
          </div>
        </div>
        <router-link
          to="/"
          class="next suc-btn"
        >
          {{ $t('commonHead.home') }}
        </router-link>
      </div>
    </div>
    <!-- /第三步 -->
    <div class="content r-footer">
      <div class="copyright">
        {{ webConfigData.pcCopyright }}
      </div>
    </div>
    <!-- 登录弹窗组件 -->
    <login-popup
      v-if="showLogin"
      @hide-login-pop="hideLoginPop"
    />
    <!-- /登录弹窗组件 -->
  </div>
</template>

<script setup>
import * as util from '@/utils/index.js'
import Cookie from 'vue-cookies'
import { encrypt } from '@/utils/crypto.js'
import { AppType } from '@/utils/constant'

const router = useRouter()

let hadGotCode = false
const mobile = ref('')
watch(() => mobile.value, () => {
  if (hadGotCode) {
    hadGotCode = false
  }
})

const webConfigStore = useWebConfigStore()
const webConfigData = computed(() => webConfigStore.pcConfig)
const serviceTermsSwitch = ref(true)
const privacyPolicySwitch = ref(true)
onMounted(() => {
  document.title = $t('register.registerAccount')
  http.get('/sys/config/info/getSysServiceSwitch').then(({ data }) => {
    serviceTermsSwitch.value = data.serviceTermsSwitch
    privacyPolicySwitch.value = data.privacyPolicySwitch
  })
})

// 输入错误提示:  1-手机号输入错误  2-验证码输入错误  3-账号输入错误  4-密码输入错误  5-验证密码输入错误
const errorTips = ref(0)
// 验证码相关
const show = ref(true)
const count = ref('')
let timer = null
/**
 * 获取验证码
 */
const getCode = () => {
  if (!util.checkPhoneNumber(mobile.value)) {
    errorTips.value = 1
    return
  }
  if (!isAgree.value) {
    errorTips.value = 6
    return
  }
  if (hadGotCode) {
    return
  }
  // 判断值
  hadGotCode = true
  errorTips.value = 0
  const sendSmsParam = {
    mobile: mobile.value
  }

  http.put('/user/sendRegisterSms', sendSmsParam).then(() => {
    const timeCount = 60
    if (!timer) {
      count.value = timeCount
      show.value = false
      timer = setInterval(() => {
        if (count.value > 0 && count.value <= timeCount) {
          count.value--
        } else {
          show.value = true
          clearInterval(timer)
          timer = null
          hadGotCode = false
        }
      }, 1000)
    }
  })
  // 判断值
  hadGotCode = false
}

/**
 * 跳转到《服务条款》或《隐私协议》
 */
const toTermsPage = (sts) => {
  router.push({
    path: '/terms-page',
    query: {
      sts
    }
  })
}

const registerStep = ref(1) // 注册步骤
const validCode = ref('')
let checkRegisterSmsFlag = '' // 校验登录注册验证码成功的标识
const password = ref('')
const confirmPwd = ref('')
// 完成跳转首页倒计时
let loTimer = null
const loCount = ref(0)
const isAgree = ref(true)
/**
 * 注册-下一步按钮
 */
const userStore = useUserStore()
const registerNext = util.debounce(() => {
  if (registerStep.value === 1) {
    if (!util.checkPhoneNumber(mobile.value)) {
      errorTips.value = 1
    } else if (!validCode.value.trim()) {
      errorTips.value = 2
    } else if (!isAgree.value) {
      errorTips.value = 6
    } else {
      errorTips.value = 0
      // 校验验证码
      const checkRegisterSmsParam = {
        mobile: mobile.value,
        validCode: validCode.value
      }
      http.put('/user/checkRegisterSms', checkRegisterSmsParam)
        .then(({ data }) => {
          checkRegisterSmsFlag = data
          registerStep.value += 1
        })
    }
  } else if (registerStep.value === 2) {
    const reg = /^(?=.*[a-zA-Z])(?=.*\d)(?=.*(\W|_))[A-Za-z\d(\W|_)]{8,20}$/
    const result = reg.test(password.value)
    if (!password.value.trim()) {
      errorTips.value = 4
    } else if (!result) {
      errorTips.value = 7
    } else if (password.value !== confirmPwd.value) {
      errorTips.value = 5
    } else {
      errorTips.value = 0
      // 请求注册
      const userRegisterParam = {
        checkRegisterSmsFlag, // 校验登录注册验证码成功的标识
        mobile: mobile.value,
        password: encrypt(password.value),
        socialType: AppType.PC
      }
      http.post('/user/register', userRegisterParam)
        .then(({ data }) => {
          registerStep.value += 1
          Cookie.set('bbcToken', data.accessToken)
          // 注册完成后获取是否为通联支付
          http.get('/sys/config/paySettlementType').then(({ data }) => {
            if (data) {
              localStorage.setItem('bbcPaySettlementType', data)
            }
            setTimeout(() => {
              router.push('/')
            }, 3000)
            const loTimeCount = 3
            if (!loTimer) {
              loCount.value = loTimeCount
              loTimer = setInterval(() => {
                if (loCount.value > 0 && loCount.value <= loTimeCount) {
                  loCount.value--
                } else {
                  clearInterval(loTimer)
                  loTimer = null
                }
              }, 1000)
            }
          })
          http.get('/p/user/userInfo', {
          }).then(({ data }) => {
            userStore.setUser({
              nickName: data.nickName,
              userId: data.userId
            })
          })
        })
    }
  }
}, 300)

// 登录弹窗
const showLogin = ref(false)
const hideLoginPop = () => {
  showLogin.value = false
}

</script>

<style lang="scss" scoped>
@use "index";
</style>
